Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → Creating custom decorators

Python Functions

Creating custom decorators

Decorators are a powerful feature in Python that allow you to modify or enhance functions and methods in a clean and readable way. They provide a way to wrap additional functionality around an existing function without modifying its core behavior. Essentially, a decorator is a function that takes another function as input and returns a modified version of that function.

The Basics

The core syntax involves the `@` symbol placed above the function definition. Let's break down a simple example:
User defined customizable decorator in python def my_decorator(func): def wrapper(): print("Before function execution") func() print("After function execution") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()

Output

Before function execution Hello! After function execution
Explanation 1. `my_decorator` is our decorator function. It takes a function (`func`) as input. 2. `wrapper` is an inner function that encapsulates the additional functionality (printing before and after). It calls the original function (`func()`). 3. `@my_decorator` is syntactic sugar. It's equivalent to `say_hello = my_decorator(say_hello)`. The decorator function is applied to `say_hello`.
Let's explore more sophisticated uses of decorators:

1. Decorator with Arguments

Sometimes, you need to pass arguments to the decorator itself. This requires a slightly more complex structure:
python Decorator with Arguments def repeat(num_times): def decorator_repeat(func): def wrapper(*args, **kwargs): for _ in range(num_times): result = func(*args, **kwargs) return result return wrapper return decorator_repeat @repeat(num_times=3) def greet(name): print(f"Hello, {name}!") greet("Alice")

Output

Hello, Alice! Hello, Alice! Hello, Alice!
Here, `repeat` is a decorator *factory*. It takes `num_times` as input and returns a decorator (`decorator_repeat`) which then decorates the function. `*args` and `**kwargs` allow the decorated function to accept any number of positional and keyword arguments.

2. Decorator with Return Values

Decorators can also modify the return value of the function:
Python Decorator with Return Values def bold_return(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) return f"{result}" return wrapper @bold_return def get_message(): return "This is a message" print(get_message())

Output

This is a message
This decorator wraps the return value in HTML bold tags.

3. Chaining Decorators

You can apply multiple decorators to a single function:
Chaining Decorators example in python def make_uppercase(func): def wrapper(*args, **kwargs): return func(*args, **kwargs).upper() return wrapper def add_exclamation(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return wrapper @make_uppercase @add_exclamation def greet2(name): return f"Hello, {name}" print(greet2("Bob"))

Output

HELLO, BOB!
Note the order of application – `add_exclamation` is applied first, then `make_uppercase`.

4. Decorators with Class Methods

Decorators are also useful with class methods:
Python Decorators with Class Methods example def log_method_call(func): def wrapper(self, *args, **kwargs): print(f"Calling method: {func.__name__} with args: {args}, kwargs: {kwargs}") result = func(self, *args, **kwargs) print(f"Method {func.__name__} finished.") return result return wrapper class MyClass: @log_method_call def my_method(self, a, b): return a + b my_instance = MyClass() print(my_instance.my_method(5,3))

Output

Calling method: my_method with args: (5, 3), kwargs: {} Method my_method finished. 8
This example logs details about method calls before and after execution.
Decorators are a powerful tool for enhancing code readability and maintainability. By mastering their usage, you can write more organized and efficient Python programs. Remember to choose the appropriate decorator structure based on the complexity of the additional functionality you need to add.

Tutorials